import {Command} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import api from 'api';
import {extraPathsValue} from '@/redux/util';
import Taro from '@tarojs/taro';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async loadGameUserInfo() {
      const gameBase = await api.MemberController.getIplandMemberBase();
      let customer = Taro.getStorageSync('b2b-wechat@login');
      if (customer.user) customer = customer.user;
      if (gameBase.nickName) {
        action.commonChange('main.defaultName', gameBase.nickName);
      }

      if (gameBase.headPortrait) {
        action.commonChange('main.defaultPictureUrl', gameBase.headPortrait);
      }

      action.commonChange('main.customer', customer);
    },
    async getMemberBase() {
      const result = await api.MemberController.getMemberBase();
      action.commonChange('main.memberInfo', result);
    },
    async setGameUserInfo(e: Record<string, any>) {
      const res = await api.MemberController.setIplandMemberBase(e);
      Taro.showToast({
        icon: 'none',
        title: '修改成功',
      });
      action.commonChange('main.defaultName', res.nickName);
      action.commonChange('main.defaultPictureUrl', res.headPortrait);
      action.commonChange('main.customer.name', res.nickName);
      action.commonChange('main.customer.pictureUrl', res.headPortrait);
      // action.commonChange('main.customer', {
      //   pictureUrl: res.context.headPortrait,
      //   name: res.context.nickName,
      // });
    },
    async submitName(name: string) {
      // let { name, typeList, sex, pictureUrl, birthDate } = this.state;
      // let userInfo = Taro.getStorageSync('b2b-wechat@login');
      const {customer} = getData().main;
      if (name.trim() == '') {
        Taro.showToast({
          title: '请输入你的昵称!',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      const params = {
        nickName: name,
        headPortrait: customer.pictureUrl,
        // id: userInfo.user.id,
        // sex: userInfo.user.sex,
        // pictureUrl: userInfo.user.pictureUrl,
        // birthDateStr: userInfo.user.birthDate || userInfo.user.birthDateStr,
      };
      // console.log(params, 'xxxxxxxxxxxxxxxxx');
      // Taro.setStorageSync('b2b-wechat@login', userInfo);
      await action.setGameUserInfo(params);
      // userInfo.user.name = name;
      Taro.hideLoading();
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageIAccountInformationMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
